<?php
namespace control;
// 配件入库
class partsInStockClass extends adIndexClass
{

    private const page = 'partsInStock';
    private const table = 'parts_inventory';
    private const tableMx = 'parts_inventory_detail';
    private const tableRecord = 'parts_inventory_record';
    private const tableTarget = 'parts';
    private const title = '配件入库';
    private const state = ['制单', '待确认', '已确认'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => "入库单号",
                        'width' => 250,
                        'sort' => 1,
                    ],
                    'supplier'  => [
                        'name'  => '供应商名称',
                        'width' => 250,
                    ],
                    'warehouse'         => [
                        'name'  => '仓库名称',
                        'width' => 250,
                    ],
                    'stid'          => [
                        'name'  => '制单人',
                        'width' => 250,
                    ],
                    'orderDate'          => [
                        'name'  => '入库日期',
                        'width' => 250,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 250,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "入库单号" => text(array("name" => "orderNo")),
                    "供应商"   => selectMultiple(["name" => "targetId", 'table' => "supplier", 'sqlId' => 'id', 'where' => "coid = '" . self::$coid . "'", 'sqlField' => 'name']),
                    '仓库名称' => selectMultiple(["name" => "warehouseId", 'table' => "warehouse", 'sqlId' => 'id', 'where' => "coid = '" . self::$coid . "'", 'sqlField' => 'name']),
                ],
                [
                    '制单人'  => selectMultiple(["name" => "stid", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name']),
                    "入库日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "状态" => select(["name" => "state", 'option' => self::state]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 列表-查询条件
     *
     * @return string
     */
    public function home(): string
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        if ($this->power(self::page, "print")) {
            $button .= " <span onclick=\"batchPrint('" . $this->get('cla') . "')\" class='spanButton'>批量打印</span>\n";
        }
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /**
     * 客户列表-查询结果
     *
     * @return bool|string
     */
    public function homeSearch(): string
    {
        //查询结果
        $where = " coid = '" . self::$coid . "' AND classify=1 ";
        $equal = [
            'targetId' => $this->post('targetId'),
            'warehouseId' => $this->post('warehouseId'),
            'stid' => $this->post('stid'),
            'state' => $this->post('state'),
        ];
        $like = [
            'orderNo' => $this->post('orderNo'),
        ];
        //生成查询语句
        $where .= search([
            "=" => $equal,
            "like" => $like,
        ]);

        if ($this->post('orderDate')) {
            $where .= self::timeComparison($this->post('orderDate'), 'date', 'orderDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        $isPrint = $this->power(self::page, "print") ? true : false;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => ["name" => "listId", "value" => $array['id']],
                "detail" => ["title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"],
                "edit" => $array['state'] !== '已确认' ? ["title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"] : [],
                'print' => ($isPrint === true) ? ['title' => '打印', 'click' => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$array['id']}')"] : [],
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'supplier':
                        $row[] = supplierClass::getName($array['targetId']);
                        break;
                    case 'warehouse':
                        $row[] = warehouseClass::getName($array['warehouseId']);
                        break;
                    case 'stid':
                        $row[] = self::findStaff($array['stid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 保存并提交
     * @return bool|string
     */
    public function saveAndCommit(): bool|string
    {
        $resultJson = $this->editEdit();
        $result = json_decode($resultJson,true);
        if ($result['warn'] == 2){
            unset($_SESSION['warn']);
            $resultJson = $this->commitEdit();
        }
        return $resultJson;
    }
    /**
     * 编辑页
     *
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id');
        $info = query(self::table, " coid = '" . self::$coid . "' AND id = '" . $id . "' ");
        $button[] = [
            'style' => 'li-btn-blue-bg',
            "name" => "保存",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
        ];
        $button[] = [
            "name" => "保存并提交",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=saveAndCommit')"
        ];
        $tr[] = ['', '编码', '配件名称', '规格', '单位', '数量', '单价（' . static::$unit . '）', '金额（' . static::$unit . '）', '备注'];

        $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by time"));
        $money = 0;
        foreach ((array)$result['array'] as $k=>$array) {
            $parts = query('parts', " id = '$array[partsId]'  ");
            $tr[] =
                [
                    componentClass::tablePperation($k+1,"delTableRow(this);calculateTotal()").
                    hidden(['name' => 'mxId[]', 'value' => $array['id']]) .
                    hidden(['name' => 'partsId[]', 'value' => $array['partsId'],]),
                    $parts['code'], $parts['name'], $parts['model'], $parts['unit'],
                    text(['name' => 'num[]', 'other' => self::digitalFiltering('numPrecision'), 'value' => self::lostZero($array['num'], 'numPrecision'), 'blur' => 'countMoney',]),
                    text(['name' => 'price[]', 'other' => self::digitalFiltering('pricePrecision'), 'value' => self::lostZero($array['price'], 'pricePrecision'), 'blur' => 'countMoney',]),
                    "<span class='total'>" . self::formattingFigure($array['num'] * $array['price']) . "</span>",
                    text(['name' => 'mxText[]', 'value' => $array['text'],]),
                ];
            $money += $array['num'] * $array['price'];
        }
        $total      = [
            5  => "<span id='total_num'>" . self::lostZero(array_sum(array_column((array)$result['array'],'num')),'num') . "</span>",
            7  => "<span id='total_money'>" . self::formattingFigure($money) . "</span>",
        ];

        $table = $this->listTable(array('tr' => $tr, 'end' => true, 'total' => $total));
        $page = self::page;
        $tableBut = <<<EOT
                <span class="smallButton" onclick="layer('{$this->get('cla')}','addMx', $('form[name={$page}EditForm]').serialize())">选择配件</span>
EOT;

        //表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . '供应商' => selectMultiple(['table' => 'supplier', "title" => '供应商', 'where' => " coid = '" . self::$coid . "' ", 'sqlField' => 'name', 'sqlId' => 'id', 'name' => 'targetId', 'value' => $info['targetId'], 'change' => 'assign']),
                    must . '仓库名称' => selectMultiple(['table' => 'warehouse', "title" => '仓库名称', 'where' => " coid = '" . self::$coid . "' AND state = '启用' ", 'sqlField' => 'name', 'sqlId' => 'id', 'name' => 'warehouseId', 'value' => $info['warehouseId'], 'change' => 'assign']),
                    must . '入库日期' => text(['name' => "orderDate", 'class' => 'text', 'value' => $info['orderDate'] ?: $this->date, 'laydate' => [],]),
                ],
                [
                    '备注' => textarea(['name' => "text", 'class' => 'text', 'value' => $info['text']]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => '选择明细',
            'button' => $tableBut,
            'html' => $table,
        ]);
        $data['html'] = $this->pageEdit([
            "html" => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
        ]);
        $data['html'] .= <<<EOT
<script>
//计算金额，税额等
function countMoney(that){
    const obj = $(that).parent().parent('tr'),
    	  num = obj.find('[name="num[]"]').val(),
    	  price = obj.find('[name="price[]"]').val()
    let total = (num * price).toFixed(amountPrecision)
    obj.find(".total").html(total)
    calculateTotal()
}
function addRow(){
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMxEdit', $("form[name='mxForm']").serialize(),function(res) {
        $("#materialTable tbody").append(res.html);
        resetNumber($("#materialTable"))
        calculateTotal()
    },'json');
}
//合计
function calculateTotal(table=''){
    table = table ? table : $('.editList')
    let num = 0,
    money = 0
    table.find("[name='num[]']").each(function(index){
        if($(this).val()){
          num+=Number($(this).val());
        }
        var moneyText = table.find(".total").eq(index).text()
        if(moneyText){
            money+=Number(moneyText);
        }
    })
    $("#total_num").text(num.toFixed(publicSettings.numPrecision.num));
    $("#total_money").text(money.toFixed(amountPrecision));
}
function assign(e) {
    let val = $(e).find("option:selected").text()
    let name = $(e).attr('name').replace('Id', '')
    $("[name="+name+"]").val(val);
}
</script>
EOT;
        //返回
        return $this->tab($data);
    }

    /**
     * 编辑报错
     *
     * @return bool|string
     */
    public function editEdit(): bool|string
    {
        $id = $this->post('id') ?: self::getId();
        $mxIdArr = $this->post('mxId') ?: [];
        $partsIdArr = $this->post('partsId');
        $priceArr = $this->post('price');
        $numArr = $this->post('num');
        $mxTextArr = $this->post('mxText');

        $field = [
            'targetId' => $this->post('targetId'),
            'warehouseId' => $this->post('warehouseId'),
            'orderDate' => $this->post('orderDate'),
            'text' => $this->post('text'),
        ];
        $annotation = [
            'targetId' => '供应商',
            'warehouseId' => '仓库',
            'orderDate' => '入库日期',
            'text' => '备注',
        ];
        $rules = [
            'targetId' => 'required',
            'warehouseId' => 'required',
            'orderDate' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
            goto resp;
        }
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (!empty($info['id']) && $info['state'] == '已确认') {
            $json['warn'] = '此入库单已确认，不能修改';
        } else {
            $this->startTrans();
            $isPass = true;//事务通过标志
            if (!$info['id']) {
                $orderNo = codeTemplateClass::generateCode(self::page, [
                    'prefix' => 'OSIN' . date('Ymd'),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => " AND coid = '" . self::$coid . "' ",
                ], $field);
                $field = array_merge($field, [
                    'id' => $id,
                    'orderNo' => $orderNo,
                    'classify' => 1,
                    'state' => '制单',
                    'coid' => self::$coid,
                    'stid' => $this->control['stid'],
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where,
                ]);
            }
            //添加或更新入库单明细
            if (is_array($mxIdArr)) {
                foreach ($mxIdArr as $k => $nid) {
                    $mx = query(self::tableMx, "id = '$nid'");
                    $parts = query('parts', "id = '$partsIdArr[$k]'");
                    $numArr[$k] = self::formattingFigure($numArr[$k], 'numPrecision');
                    if (static::isNull($parts['id'])) {
                        continue;
                    }
                    if (!empty($mx['id'])) {
                        //更新
                        $warn = static::update([
                            "table" => self::tableMx,
                            "field" => [
                                'partsId' => $parts['id'],
                                'num' => $numArr[$k],
                                'price' => $priceArr[$k],
                                'money' => self::formattingFigure($numArr[$k] * $priceArr[$k]),
                                'text' => $mxTextArr[$k],
                            ],
                            "where" => " id = '$nid'",
                        ]);
                    } else {
                        //新增
                        $warn = static::insert([
                            "table" => self::tableMx,
                            "field" => [
                                'id' => $nid,
                                'coid' => self::$coid,
                                'orderId' => $id,
                                'partsId' => $parts['id'],
                                'num' => $numArr[$k],
                                'price' => $priceArr[$k],
                                'money' => self::formattingFigure($numArr[$k] * $priceArr[$k]),
                                'text' => $mxTextArr[$k],
                            ],
                        ]);
                    }
                    if (!in_array($warn, ['新增成功', '更新成功'])) {
                        $isPass = false;
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass) {
                $this->commitTrans();
                delete(['table' => self::tableMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"]);
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            } else {
                $this->rollback();
            }
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * @return bool|string
     */
    public function addMx(): bool|string
    {
        if (static::isNull($this->post('warehouseId'))) {
            return json_encode(['warn' => '请选择仓库', 320]);
        } else {
            $callback = $this->post('callback') ? $this->post('callback') : self::page;
            $tableMx = $this->post('tableMx');
            $html =
                select(["name" => "type", "title" => "类别", 'option' => explode('，', para('partsType'))])
                . text(["name" => "code", "title" => "编码"])
                . text(["name" => "name", "title" => "名称"])
                . text(["name" => "model", "title" => "规格型号"])
                . hidden(["name" => "warehouseId", 'value' => $this->post('warehouseId')])
                // . hidden(["name" => "state", 'value' => $this->post('state') ?? '在库'])
                . hidden(["name" => "tableMx", 'value' => $tableMx])
                . hidden(['name' => 'orderId', 'value' => $this->post('orderId')]);
            $button = "<input style='margin-left: 5px' onclick=\"addRow();$('#" . self::page . "AddMx').remove()\" type='button' class='searchSub' value='提交'>";
            $html = $this->search($html);
            return $this->layer(["title" => "添加", "height" => 600, "width" => 1100, "html" => $html, "button" => $button]);
        }
    }

    /**
     *添加物料
     */
    public function addMxSearch(): bool|string
    {
        $partsId = $this->post('partsId') ? explode(',', $this->post('partsId')) : [];
        $where = " 1=1 and id not in ('" . implode("','", $partsId) . "')";
        // $and     = " AND coid = '" . self::$coid . "' AND id IN (SELECT partsId FROM parts_inventory_record WHERE warehouseId = '" . $this->post('warehouseId') . "' )  ";
        $and = " AND coid = '" . self::$coid . "' ";
        $like = [
            'name' => $this->post('name'),
            'code' => $this->post('code'),
            'model' => $this->post('model'),
        ];
        $equal = [
            'state' => '启用',
            'type' => $this->post('type'),
        ];
        $where .= search(["like" => $like, "=" => $equal]) . $and;
        $page = $this->page([
            "table" => "parts",
            "where" => $where,
            'pageNum' => 50,
            "order" => " `time` ASC",
        ]);
        //获取表头
        $checkAll = $this->checkAll("mxForm", "mxId");
        $tr[] = [$checkAll, '类别', '编码', '配件名称', '规格', '单位'];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = [
                "box" => ["name" => "mxId", "value" => $array['id']],
            ];
            $tr[] = [
                $this->dominate($dominate),
                $array['type'],
                $array['code'],
                $array['name'],
                $array['model'],
                $array['unit'],
            ];
        }
        $json['html'] = $page['hint'] .
            "<form name='mxForm'>" .
                hidden(['name' => 'warehouseId', 'value' => $this->post('warehouseId')]) .
                $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) .
            "</form>" .
            $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function addMxEdit(): bool|string
    {
        $mxIdArr = $this->post('mxId');
        $warehouseId = $this->post('warehouseId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = '请选择物料';
        } else {
            $tr = [];
            foreach ($mxIdArr as $mxId) {
                $parts = query('parts', "id = '$mxId'");
                if (static::isNull($parts['id'])) {
                    continue;
                }
                $id = self::getId();
                $tr[] =
                    [
                        componentClass::tablePperation('',"delTableRow(this);calculateTotal()").
                        hidden(['name' => 'mxId[]', 'value' => $id]) .
                        hidden(['name' => 'partsId[]', 'value' => $parts['id'],]),
                        $parts['code'],
                        $parts['name'],
                        $parts['model'],
                        $parts['unit'],
                        text(['name' => 'num[]', 'other' => self::digitalFiltering('numPrecision'), 'value' => '', 'blur' => 'countMoney',]),
                        text(['name' => 'price[]', 'other' => self::digitalFiltering('pricePrecision'), 'value' => '', 'blur' => 'countMoney',]),
                        "<span class='total'>0</span>",
                        text(['name' => 'mxText[]', 'value' => '']),
                    ];
            }
            $json['warn'] = 2;
            $json['html'] = $this->tableMany(['tr' => $tr, 'thead' => false]);
        }
        return json_encode($json, 320);
    }


    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " coid = '" . self::$coid . "' AND id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );

            $button = [];
            if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
                $button[] = [
                    "name" => "确认",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'confirm', "id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
                $button[] = [
                    "name" => "取消",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'cancel', "id" => $info['id']],
                ];
            }
            if ($info['state'] != '已确认') {
                if ($this->power(self::page, "edit") && $info['state'] == '制单') {
                    //按钮
                    $button[] = [
                        "name" => "编辑",
                        "type" => "顶部页卡",
                        "title" => "编辑用户",
                        "url" => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],
                        'style' => 'li-btn-blue-bg',
                    ];
                    //按钮
                    $button[] = [
                        "name" => "提交",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'commit', "id" => $info['id']],
                    ];
                }
                if ($this->power(self::page, "edit")) {
                    //按钮
                    $button[] = [
                        "name" => "删除",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'del', "id" => $info['id']],
                    ];
                }
            }
            //操作记录
            $button[] = self::operateLogBut($info['id']);

            $mxtr[] = ['编码', '配件名称', '规格', '单位', '数量', '单价（'.static::$unit.'）', '金额（'.static::$unit.'）', '备注'];
            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by time"));
            foreach ($result['array'] as $array) {
                $parts = query('parts', " id = '$array[partsId]'");
                $mxtr[] = [
                    $parts['code'],
                    $parts['name'],
                    $parts['model'],
                    $parts['unit'],
                    self::lostZero($array['num'], 'numPrecision'),
                    self::lostZero($array['price'], 'pricePrecision'),
                    self::formattingFigure($array['num'] * $array['price']),
                    $array['text'],
                ];
            }
            $res = find(['table' => self::tableMx, 'field' => " IFNULL(sum(num), 0) as num, IFNULL(sum(num*price), 0) as total", 'single' => "orderId = '$info[id]' group by orderId",]);
            $nums = $total = 0;
            if (!static::isNull($res)) {
                $nums = self::lostZero($res['num'],'numPrecision');
                $total = self::formattingFigure($res['total']);
            }
            $total_tr = [
                    4=>$nums,
                    6=>$total,
            ];
            $mxButton = '';
            if ($this->power(self::page, "edit") && $info['state'] == '制单') {
                $mxButton .= "<a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=downloadModel' class='smallButton'>导入模板</a>
                    <span onclick=\"document.excelForm.file.click()\" class='smallButton'>Excel 导入</span>\n" .
                    '<form name="excelForm" class="hide" method="post" enctype="multipart/form-data" action="' . root . 'control/adIndex.html?cla=' . $this->get['cla'] . '&fun=importData&orderId=' . $info['id'] . '">
                         <input name="file" type="file" onchange="document.excelForm.submit()">
                    </form>';
            }
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow([
                [
                    [
                        "供应商名称" => query('supplier', " id = '{$info['targetId']}' ", 'name')['name'],
                        "仓库名称" => query('warehouse', " id = '{$info['warehouseId']}' ", 'name')['name'],
                        "单据日期" => $info['orderDate'],
                        "入库单号" => $info['orderNo'],
                    ],
                    [
                        "制单人" => self::findStaff($info['stid']),
                        "状态" => $info['state']
                    ],
                    [
                        "备注" => pre($info['text']),
                    ],
                ],
            ]);
            $data['html'] .= $this->detailList([
                'title' => '入库明细',
                'button' => $mxButton,
                'html' => $this->listTable(array('tr' => $mxtr, 'showEmpty' => true, 'total' => $total_tr, 'showSort' => true)),
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    /**
     * 导出
     */
    public function downloadModel()
    {
        if (!$this->power(self::page, 'edit')) {
            $_SESSION['warn'] = '你还没有编辑的权限';
        } else {
            $title = ['*配件编码', '配件名称', '*数量', '单价（'.static::$unit.'）', '备注'];
            $data[] = ['EQ0001', '贴标机机头', 10, 1, '样例数据'];
            $text = $this->control['name'] . "导出了" . self::title . "导入模板";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, self::title . ".xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }

    /**
     * Excel导入
     */
    public function importData()
    {
        $orderId = $this->get('orderId');
        if (!$this->power(self::page, 'edit')) {
            $_SESSION['warn'] = '你还没有编辑的权限';
        } elseif (empty($orderId)) {
            $_SESSION['warn'] = '未找到ID';
        } else {
             $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
            $x = 0;
            $text = '';
            foreach ($data as $i => $row) {
                if ($i > 0) {
                    $k = formSubArray($row);
                    $parts = query('parts', " coid = '" . self::$coid . "' AND code = '$k[0]'");
                    $field = [
                        'partsId' => $parts['id'],
                        'num' => $k[2],
                        'price' => $k[3],
                        'money' => round($k[2] * $k[3], 2),
                        'unit' => $parts['unit'],
                        'text' => $k[4]
                    ];
                    $annotation = [
                        'partsId' => '配件',
                        'num' => '数量',
                    ];
                    $rules = [
                        'partsId' => 'required',
                        'num' => 'required',
                    ];
                    // 校验是否符合规则
                    $vt = new \verify();
                    $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                    if ($result === false) {
                        $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
                        $text .= "第【{$i}】行：" . $vt->getErrs()[0] . "<br>";
                    } else {
                        $where = " coid = '" . self::$coid . "' and orderId = '{$orderId}' AND partsId = '{$parts['id']}'";
                        $mx = query(self::tableMx, $where, 'id');
                        if (empty($mx['id'])) {
                            $field['id'] = suiji();
                            $field['coid'] = self::$coid;
                            $field['orderId'] = $orderId;
                            $warn = static::insert(["table" => self::tableMx, "field" => $field]);
                        } else {
                            $warn = static::update(["table" => self::tableMx, "field" => $field, 'where' => " id = '" . $mx['id'] . "' "]);
                        }
                        if (in_array($warn, ['新增成功', '更新成功'])) {
                            // 更新数量
                            $x++;
                            $text .= "第【{$i}】行导入成功<br>";
                        } else {
                            $text .= "第【{$i}】行导入失败：更新失败<br>";
                        }
                    }
                }
            }
            $warn = "成功导入{$x}条数据";
            $this->logText(["type" => self::page, "text" => $text]);
            $_SESSION['warn'] = $warn;
        }
        $locationUrl = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $orderId;
        header("Location:" . $locationUrl);
        exit(0);
    }

    /**
     * 确认
     */
    public function confirmEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " coid = '" . self::$coid . "' AND id = '$id'");
        $field = [
            'state' => '已确认',
            'confirmTime' => $this->time,
        ];
        if (!$this->power(self::page, 'confirm')) {
            $json['warn'] = '你还没有确认权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此入库单';
        } elseif ($info['state'] != '待确认') {
            $json['warn'] = '此入库单不是待确认状态，不能确认';
        } else {
            $this->startTrans();
            $isPass = true; // 事务通过标志
            $json['warn'] = static::update([
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ]);
            if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass === true) {
                $details = find([
                    'table' => self::tableMx,
                    'where' => " orderId = '{$info['id']}'",
                ]);
                foreach ($details['array'] as $key => $value) {
                    static::insert([
                        'table' => self::tableRecord,
                        'field' => [
                            'id' => self::getNo(),
                            'coid' => self::$coid,
                            'warehouseId' => $info['warehouseId'],
                            'partsId' => $value['partsId'],
                            'num' => $value['num'],
                            'inventoryId' => $info['id'],
                            'inventoryMxId' => $value['id'],
                        ],
                    ]);
                }
                $this->commitTrans();//提交事务
                auditingFollow([
                    "type" => "配件入库",
                    "typeId" => $info['id'],
                    "text" => "【{$this->control['name']}】确认",
                ]);
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 取消
     */
    public function cancelEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " coid = '" . self::$coid . "' AND id = '$id'");
        $field = [
            'state' => '制单',
            'commitTime' => '',
        ];
        if (!$this->power(self::page, 'cancel')) {
            $json['warn'] = '你还没有取消权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此入库单';
        } elseif ($info['state'] == '已确认') {
            $json['warn'] = '此入库单是已确认状态，无法取消';
        } else {
            $json['warn'] = static::update([
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ]);
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                auditingFollow(array(
                    "type" => "配件入库",
                    "typeId" => $info['id'],
                    "text" => "【{$this->control['name']}】取消",
                ));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 提交
     */
    public function commitEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " coid = '" . self::$coid . "' AND id = '$id'");
        $field = [
            'state' => '待确认',
            'commitTime' => $this->date,
        ];
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此入库单';
        } elseif ($info['state'] != '制单') {
            $json['warn'] = '此入库单不是制单状态，不能提交';
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                auditingFollow([
                    "type" => "配件入库",
                    "typeId" => $info['id'],
                    "text" => "【{$this->control['name']}】提交",
                ]);
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = $word = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            case 'confirm':
                $act = 'confirm';
                $msg = '确认';
                $title = '是否确认此入库单，确认后将不可修改？';
                $function = 'confirmEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'commit':
                $act = 'edit';
                $msg = '编辑';
                $title = '是否确认提交此入库单？';
                $function = 'commitEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'cancel':
                $act = 'cancel';
                $msg = '撤回';
                $title = '是否确认取消此入库单？';
                $function = 'cancelEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm, quoForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     *
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " coid = '" . self::$coid . "' AND id = '$id' ");
                if ($info['state'] == '已确认') {
                    $warn = "删除失败：已确认，暂不能删除";
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                    delete(array("table" => 'auditing_follow', "where" => " typeId = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }


	/**
	 * 批量打印
	 *
	 * @return string
	 */
	public function batchPrint(): string
	{
		$lists = $this->get('lists');
		if(empty($lists)){
			exit('参数错误');
		}else{
			$listId = base64_decode($lists, true);
			$array = explode(',', $listId);
			$data = [];
			foreach ($array as $id){
				$data[] = static::printPage($id, false);
			}
			return (new printTemplateClass())->start(self::page, $data);
		}
	}

	/**
	 * 打印
	 *
	 * @return string
	 */
	public function printPage($param = '', $isReturn = true): string|array
	{
		$id                  = $param ?: $this->get('id');
		$info                = query(self::table, " id = '$id'");
        $info['companyName'] = query('company', "coid = '" . self::$coid . "'")['name']; //公司名称//公司名称
        $info['title'] = self::title;
        $info['printTime'] = $this->time;
        $info['stid'] = self::findStaff($info['stid']);
        $info['targetId'] = query('supplier', "id = '$info[targetId]'")['name'];
        $info['warehouseId'] = query('warehouse', "id = '$info[warehouseId]'")['name'];
        $info['qr'] = "source=" . self::page . "&id=" . $info['id'];
        $detail = find(['table' => self::tableMx, 'where' => " orderId = '$info[id]' order by time asc"])['array'];
        $items = [];
        $x = 1;
        $totalNum = $totalPrice = $totalMoney = 0;
        foreach ($detail as $array) {
            $parts = query(self::tableTarget, "id = '$array[partsId]'");
            $total = round($array['price'] * $array['num'], 2);
            $items[] = [
                'no' => $x,
                'code' => $parts['code'],
                'name' => $parts['name'],
                'model' => $parts['model'],
                'num' => self::lostZero($array['num'], 'numPrecision'),
                'price' => self::lostZero($array['price'], 'pricePrecision'),
                'money' => self::lostZero($total),
                'text' => $array['text'],
            ];
            $x++;
            $totalPrice += $array['price'];
            $totalMoney += $total;
            $totalNum += $array['num'];
        }
        $append = [
            'no' => '合计',
            'num' => self::lostZero($totalNum, 'numPrecision'),
            'price' => self::lostZero($totalPrice, 'pricePrecision'),
            'money' => self::lostZero($totalMoney),
        ];
        $items[] = $append;
        $info['detail'] = $items;
	    if ($isReturn) {
		    return (new printTemplateClass())->start(self::page, $info);
	    } else {
		    return $info;
	    }
    }

}
